package com.hzqy.web.ac.epg;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hzqy.commons.utils.HttpGetQRCodeUtil;
import com.hzqy.commons.utils.HttpUtil;
import com.hzqy.commons.utils.MD5Util;
import com.hzqy.commons.utils.SystemConfigUtils;
import com.hzqy.commons.utils.WChatUtils;
import com.hzqy.service.epg.AcInterfaceServiceBean;
import com.hzqy.service.epg.WchatTvOrgService;
import com.hzqy.web.login.SessionKey;
import com.hzqy.web.vo.epg.AcInterfaceVo;
import com.hzqy.web.vo.epg.gcw.AcGcwYlVo;

@Controller
@RequestMapping("/external")
public class AcInterfaceAction {
	private static final Log LOG = LogFactory.getLog(AcInterfaceAction.class);
	private static final String CHARSET = "UTF-8";
	private static final String _companyid = "hzkdHQepg";
	//private static final String key = "#kdVer@zZ";
	private static final String key = SystemConfigUtils.getSysConfig("acInterfaceKey");

	@Resource
	private WchatTvOrgService service;
	@Resource
	private AcInterfaceServiceBean interfaceServiceBean;
	
	/**
	 * 边锋注入接口
	 *  约定： 每次插入最多30条
	 *  token:
	 *  companyid:
	 */
	@RequestMapping(value = "/bfInsert")
	@ResponseBody
	public Object bfInsert(@RequestParam("params") String params,
			@RequestParam("token") String token,
			@RequestParam("companyid") String companyid
			){
		Map<Object,Object> map = new HashMap<>();
		if(!_companyid.equals(companyid)) {
			map.put("msg","渠道编号认证失败");
			map.put("result", "-2");
			return map;
		}
		String _token = getToken();
		if(!_token.equals(token)) {
			map.put("msg","签名认证失败");
			map.put("result", "-3");
			return map;
		}
		JSONObject object= JSONObject.parseObject(java.net.URLDecoder.decode(params));
		//json转对象
		List<AcInterfaceVo> listVo = JSONObject.parseArray(object.get("data").toString(),AcInterfaceVo.class);
		if(listVo.size()>10) {
			map.put("msg", "超出最大传输数据");
			map.put("result", "-1");
			return map;
		}
		if(listVo.size()==0) {
			map.put("msg", "无数据");
			map.put("result", "-4");
			return map;
		}
		List<String> errorList = new ArrayList<>();
		for(int i=0;i<listVo.size();i++) {
			//查询数据库是否存在当前用户，有则跳过，无则插入 --- 1则已插入，-1异常
			AcInterfaceVo acVo = listVo.get(i);
			int result = service.selectInsertBF(acVo);
			if(result == -1) {
				//插入失败用户 返回边锋
				errorList.add(acVo.getUserPhone());
			}
		}
		if(errorList.size() > 0) {
			map.put("msg", "存在入库失败用户，并返回失败用户");
			map.put("result", "0");
			map.put("list", errorList);
			return map;
		}
		map.put("msg", "边锋数据入库成功");
		map.put("result", "1");
		return map;
	}
	
	/**
	 * 广场舞与（有料、服务）接口，负责获取用户在(有料签到、服务微厅签到)的票数同步。
	 * 如果调用失败，有料将发起重试，重试2次。
	 * @param ayv
	 * @param userid 业务账号
	 * @param number 票数
	 * @param inputtime 获取票数的时间，格式为yyyyMMddHHmmss
	 * @return result_code 0为成功，其他为失败。message 返回消息描述
	 */
	@RequestMapping("/gcw_vote_json")
	@ResponseBody
	public Object gcwVoteJson(@RequestBody AcGcwYlVo ayv) {
		Map<String,String> map = interfaceServiceBean.processGcwGdToCmtt(ayv);
		return map;
	}
	
	/**
	 * 与gcwVoteJson的action业务功能一至，此action支持非json格式接口
	 * @param ayv
	 * @return
	 */
	@RequestMapping("/gcw_vote")
	@ResponseBody
	public Object gcwVote(AcGcwYlVo ayv) {
		Map<String,String> map = interfaceServiceBean.processGcwGdToCmtt(ayv);
		return map;
	}
	
	public static String getToken() {
		String token = "";
		try {
			token = new String(Base64.encodeBase64(DigestUtils.md5((_companyid+key).getBytes(CHARSET))), CHARSET);
			
			//System.out.println(DigestUtils.md5((_companyid+key)));
			//new String(Base64.encodeBase64(DigestUtils.md5((_companyid+key).getBytes(CHARSET))), CHARSET);
			//System.out.println("md5:"+(MD5Util.MD5_32bit(_companyid+key)).getBytes());
		} catch (Exception e) {
			LOG.debug("base64+md5加密异常");
		}
		return token;
	}

	//------------------test----------------------------------------
	public static void main(String[] args) throws IOException {
		Map<String,Object> map = test();
		//String url = "http://10.255.247.124:8083/serve-front/api/service/qrcode.do?account=0571000429&username=itv&userkey=c2ccee995150d9b4c82f9d4fce3266f1";
		//Map<String, String> str  = getQRCode();
		//System.out.println(str.get("picUrl"));
	}

	public static Map<String,Object> test() {
		/*Map<String,String> map = new HashMap<>();
		map.put("username", "sujz");
		map.put("password", "123");*/
		Map<String,Object> map2 = new HashMap<>();
		
		/*List<AcInterfaceVo> list = new ArrayList<>();
		AcInterfaceVo acfv = new AcInterfaceVo();
		acfv.setUserPhone("13733333333");
		acfv.setUserName("秀秀");
		acfv.setAreaName("王马社区");
		acfv.setIptvid("0571000");
		AcInterfaceVo acfv1 = new AcInterfaceVo();
		acfv1.setUserPhone("1322222222");
		acfv1.setUserName("明明");
		acfv1.setAreaName("婺江社区");
		acfv1.setIptvid("0571002");
		AcInterfaceVo acfv2 = new AcInterfaceVo();
		acfv2.setUserPhone("1515151515");
		acfv2.setUserName("妮妮");
		acfv2.setAreaName("近江西园社区");
		acfv2.setIptvid("0571001");
		AcInterfaceVo acfv3 = new AcInterfaceVo();
		acfv3.setUserPhone("18058807778");
		acfv3.setUserName("手机号");
		acfv3.setAreaName("测试环境");
		acfv3.setIptvid("0571");
		list.add(acfv);
		list.add(acfv1);
		list.add(acfv2);
		list.add(acfv3);
		map2.put("data", list);*/
		return map2;
	}
	
	 /**
     * 接口调用公共类
     * @throws IOException
     */
    public static String postCommon(Map<String, Object> paramMap, String url, String method) throws IOException {
        JSONObject json = JSONObject.parseObject(JSON.toJSONString(paramMap));
        String paramStr = String.valueOf(json);
        String encodeStr = java.net.URLEncoder.encode(paramStr);
        //System.out.println("param测试数据："+paramStr);

        Map<String, String> treeMap = new TreeMap<String, String>();
       
        String params = "&params="+paramStr;//"appid="+BIANFENG_APPID+"&param="+encodeParam+"&signature="+mapStr;
        String sendResult = null;
        String token = getToken();

        //System.out.println("请求地址："+url+"?"+params);
        url = url+"?token="+token+"&companyid="+_companyid+params;
        System.out.println("url:"+url);
        if(method.equals("post")){
            sendResult = WChatUtils.sendPost(url, "");
        }else{
            sendResult = WChatUtils.sendGet(url);
        }
        return sendResult;
    }
	 /**
     * 获取二维码接口--激活电信产品
     * get
     * 服务器用私网地址：172.30.0.185  ，客户端用：10.255.247.124
     * @param account
     * @param qrcode_url=http://172.30.0.185:8083/serve-front/api/service/qrcode.do
     * @param username=itv
     * @param userkey=c2ccee995150d9b4c82f9d4fce3266f1
     * @param qrcode_path_url=http://10.255.247.124:8083/serve-front
     * @param type=sq 获取绑定二维码时不需要传此参数，获取领票二维码时传固定type=sq
     * return:picUrl:二维码图片
     */
    @RequestMapping("/getGCWQRCode")
	@ResponseBody
    public static Map<String, String> getQRCode(HttpSession session) throws IOException {
    	Map<String, String> returnMap=new HashMap<>();
    	String userid= (String) session.getAttribute(SessionKey.SESSION_SERVERID);
    	String qrcode_url = SystemConfigUtils.getSysConfig(SessionKey.SESSION_SYSTEM_CONFIG.qrcode_url.getKey());
    	String qrcode_path_url = SystemConfigUtils.getSysConfig(SessionKey.SESSION_SYSTEM_CONFIG.qrcode_path_url.getKey());
    	String qrcode_username = SystemConfigUtils.getSysConfig(SessionKey.SESSION_SYSTEM_CONFIG.qrcode_username.getKey());
    	String qrcode_userkey = SystemConfigUtils.getSysConfig(SessionKey.SESSION_SYSTEM_CONFIG.qrcode_userkey.getKey());
    	String qrcode_type = SystemConfigUtils.getSysConfig(SessionKey.SESSION_SYSTEM_CONFIG.qrcode_type.getKey());
		String url = qrcode_url+"?account="+userid+"&username="+qrcode_username+"&userkey="+qrcode_userkey+"&type="+qrcode_type;
    	Map<String, String> map = HttpGetQRCodeUtil.get(url);
		String success = (String)map.get("success");
		JSONObject jsona = null;
		if("1".equals(success)){
			jsona =  JSONObject.parseObject(map.get("msg").toString());
			if("0".equals(jsona.getString("result_code"))){//成功
				returnMap.put("picUrl", qrcode_path_url+jsona.getString("qrurl"));
			}
			returnMap.put("result_msg", jsona.getString("result_msg"));
			returnMap.put("result_code", jsona.getString("result_code"));
		}else{
			returnMap.put("result_msg", "获取二维码失败!");
			returnMap.put("result_code", "-1");
			LOG.error("获取二维码失败!");
		}
        return returnMap;
    }
}
